package com.vrp3d.common.interceptor;

import com.vrp3d.common.context.InvokerContext;
import com.vrp3d.common.enums.CommonEnum;
import com.vrp3d.common.utils.DateUtil;
import com.vrp3d.common.utils.IpUtil;
import com.vrp3d.common.utils.ObjUtil;
import com.vrp3d.domain.model.UserContext;
import com.vrp3d.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 *
 * @author vrp3d
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 打印用户请求路径
        String ip = IpUtil.getRealIp(request);
        log.info("IP地址:{},请求路径:{}", ip, request.getRequestURL());

        // 判断用户选择的是哪国语言(前后端自定义header参数)
        String headerUserLanguage = request.getHeader(CommonEnum.USER_LANGUAGE.getMsg());
        if (StringUtils.isNotBlank(headerUserLanguage)) {
            UserContext userCtx = InvokerContext.getUserCtx();
            if (ObjUtil.isNotEmpty(userCtx)) {
                if (null != userCtx.getId()) {
                    String redisUserLanguage = redisService.query(CommonEnum.REDIS_USER_LANGUAGE.getMsg() + userCtx.getId());
                    if (StringUtils.isNotBlank(redisUserLanguage)) {
                        if (!redisUserLanguage.equals(headerUserLanguage)) {
                            redisService.putCacheWithExpireTime(CommonEnum.REDIS_USER_LANGUAGE.getMsg() + userCtx.getId(), headerUserLanguage, DateUtil.SECONDS_PER_HOUR);
                        }
                    } else {
                        redisService.putCacheWithExpireTime(CommonEnum.REDIS_USER_LANGUAGE.getMsg() + userCtx.getId(), headerUserLanguage, DateUtil.SECONDS_PER_HOUR);
                    }
                }
            }
            // todo 没有登录的情况下  如何记录header
        }
        return true;
    }

}
